package common

import (
	"company_website/src/global"
	"company_website/src/model/common"
	"company_website/src/model/request"
	"company_website/src/model/response"
	"company_website/src/server"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"sync"
)

type New struct{}

var service = *server.ServerComment

func (n *New) GetNewList(c *gin.Context) {
	var getNewList = response.GetNewList{}
	page := common.PageReqInfo{}
	if err := c.ShouldBind(page); err != nil {
		//c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		response.FailWithMessage("数据输入错误导致绑定失败", c)
		return
	} else {
		offset := (page.CurrentPage - 1) * page.PageSize
		getNewList.PageReqInfo = &page
		result := global.GVL_DB.Offset(offset).Order("id desc").Where("status = ?", 1).Limit(6).Find(&getNewList.News.News)
		if result.Error != nil {
			//c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			response.Result(response.ERROR, nil, result.Error.Error(), c)
		} else {
			response.Result(response.SUCCESS, getNewList.News, "Get newList success", c)
			//c.JSON(http.StatusOK, getNewList.News)
		}
	}
}
func (n *New) GetNewInfoById(c *gin.Context) {
	var newsID = request.NewID{}
	var NewInfo = response.GetNewInfoById{}
	if err := c.ShouldBind(&newsID); err != nil {
		//c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		response.FailWithMessage("数据输入错误导致绑定失败", c)
		return
	} else {
		tx := global.GVL_DB.Where("id= ?", newsID.Id).Select("title,content,time,status") // 添加更多条件，如：.And("age > ?", 18)
		// 执行查询
		result := tx.Find(&NewInfo)
		if result.Error != nil {
			response.Result(response.ERROR, nil, result.Error.Error(), c)
			//c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
		} else if NewInfo.Status == 0 {
			response.Result(response.ERROR, nil, " Info is not exist", c)
		} else {
			response.Result(response.SUCCESS, NewInfo.GetNewResInfo, "Get newInfoById success", c)
			//c.JSON(http.StatusOK, NewInfo.GetNewResInfo)
		}
	}
}

func (n *New) KnowMoreNewInfo(c *gin.Context) {
	var KnowMoreNews = response.KnowMoreNews{}
	var pageInfo = common.PageReqInfo{}
	if err := c.ShouldBind(&pageInfo); err != nil {
		//c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		response.FailWithMessage("数据输入错误导致绑定失败", c)
	} else {
		offset := (pageInfo.CurrentPage - 1) * pageInfo.PageSize
		result := global.GVL_DB.Where("status=1").Offset(offset).Limit(pageInfo.PageSize).Find(&KnowMoreNews.KnowMoreNewsInfo)
		if result.Error != nil {
			response.Result(response.ERROR, nil, result.Error.Error(), c)
		} else {
			c.JSON(http.StatusOK, &KnowMoreNews.KnowMoreNewsInfo)
			response.Result(response.SUCCESS, &KnowMoreNews.KnowMoreNewsInfo, "Get more newInfo success ", c)
		}
	}
}

func (n *New) SearchNew(c *gin.Context) {
	var ReqInfo = request.NewType{}
	var RequestInfo = response.SearchArticles{}
	ReqInfo.ReqPageInfo = &common.PageReqInfo{}
	err := c.ShouldBind(&ReqInfo)
	if err != nil {
		//response.Result(401,nil,"")
		response.FailWithMessage("数据输入错误导致绑定失败", c)
		//c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
	} else {
		db := service.Paginate(*ReqInfo.ReqPageInfo, global.GVL_DB)
		result := db.Where("status = ? and title=? and type=?", 1, ReqInfo.Title, ReqInfo.Type).Find(&RequestInfo.Articles)
		if result.Error != nil {
			response.Result(response.ERROR, nil, result.Error.Error(), c)

			//c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
		} else {
			//c.JSON(http.StatusOK, RequestInfo)
			response.Result(response.SUCCESS, RequestInfo, "Serch new success", c)
		}
	}
}

func (n *New) PublishNew(c *gin.Context) {
	var wg = sync.WaitGroup{}
	var ReqInfo = request.NewInfo{}
	if err := c.ShouldBind(&ReqInfo); err != nil {
		//response.Result(401, nil, "the user is not logged in",c)
		response.FailWithMessage("数据输入错误导致绑定失败", c)
		return
	}
	// 使用通道来接收goroutine的结果
	resultChan := make(chan error)
	// 在goroutine中处理数据库操作
	wg.Add(1)
	go func() {
		defer wg.Done()
		defer func() {
			if r := recover(); r != nil {
				// 在goroutine中处理panic并发送错误
				resultChan <- fmt.Errorf("panic occurred: %v", r)
			}
		}()
		tx := global.GVL_DB.Begin() //开启事务
		if err := tx.Error; err != nil {
			resultChan <- err
			return
		}
		defer tx.Rollback() // 确保在发生错误时回滚
		if ReqInfo.Status == 1 {
			panic("该新闻已经存在")
			return
		} else if ReqInfo.Status == 0 {
			ReqInfo.Status = 1
			if err := tx.Create(&ReqInfo).Error; err != nil {
				resultChan <- err
				return
			}
		}
		if err := tx.Commit().Error; err != nil {
			resultChan <- err
			return
		}
		resultChan <- nil
	}()
	if err := <-resultChan; err != nil {
		response.Result(400, nil, err.Error(), c)
		//c.JSON(409, gin.H{"Error": err.Error()})
	} else {
		response.Result(200, nil, "Post successful", c)
		//c.JSON(200, gin.H{"New": "Post Successful"})
	}
	wg.Wait()
}
